package com.example.houtai.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.houtai.config.Logger;
import com.example.houtai.entity.SysUser;
import com.example.houtai.entity.SysUserRole;
import com.example.houtai.service.ISysUserRoleService;
import com.example.houtai.service.ISysUserService;
import com.example.houtai.service.ITbTokenService;
import com.github.pagehelper.PageInfo;
import com.org.dto.UserDto;
import com.org.vo.ResultEntity;
import com.org.vo.SysUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 系统用户 前端控制器
 * </p>
 *
 * @author wgq
 */
@RestController
@RequestMapping("/sys/user")
@Slf4j
public class SysUserController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysUserRoleService userRoleService;

    @Autowired
    private ITbTokenService tbTokenService;

   /* @Autowired
    private RedisTemplate redisTemplate;*/

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("/updatepassword")
    public ResultEntity updatePassword(@RequestBody SysUser sysUser){
        if (!redisTemplate.hasKey(sysUser.getMobile())){
            return ResultEntity.error("验证码已过期!!", false);
        }
        String o = (String) redisTemplate.opsForValue().get(sysUser.getMobile());
        if (o.equals(sysUser.getCode())){
            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
            wrapper.eq("mobile", sysUser.getMobile());
            SysUser userServiceOne = userService.getOne(wrapper);
            if (BeanUtil.isEmpty(userServiceOne)){
                return ResultEntity.error("用户不存在!!", false);
            }

            String encode = passwordEncoder.encode(sysUser.getPassword());
            userServiceOne.setPassword(encode);
            boolean b = userService.updateById(userServiceOne);
            if (b){
                return ResultEntity.ok("修改成功",true);
            }
            return ResultEntity.error("修改失败!!", false);
        }
        return ResultEntity.error("验证码错误!!", false);
    }

    @RequestMapping("list")
//    @Logger("用户列表")
    public ResultEntity list(@RequestBody UserDto userDto) {
        System.err.println(userDto);
        PageInfo<UserDto> list = userService.lists(userDto);
        return ResultEntity.ok("200", list);
    }


    @RequestMapping("save")
    @Transactional
    public ResultEntity save(@RequestBody UserDto userDto) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userDto,user);
        user.setPassword(passwordEncoder.encode(userDto.getPassword()));
        if (userDto.getCityids().length>0){

            String[] cityids = userDto.getCityids();
            for (int i = 0; i < cityids.length; i++) {
                if (i == 0) {
                    user.setProvince(cityids[i]);
                }
                if (i == 1) {
                    user.setCity(cityids[i]);
                }
                if (i == 2) {
                    user.setCountry(cityids[i]);
                }
            }
        }
        userService.save(user);
        System.err.println("===增加后的user==" + user);

        if (userDto.getJueseids().length > 0) {
            String[] jueseids = userDto.getJueseids();
            for (String jueseid : jueseids) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(user.getUserId());
                sysUserRole.setRoleId(Long.parseLong(jueseid));
                userRoleService.save(sysUserRole);
            }
        }
        return ResultEntity.ok("200", "添加成功", null);
    }


    @RequestMapping("delete")
    public ResultEntity delete(@RequestBody UserDto userDto) {

        SysUser sysUser = new SysUser();
        sysUser.setUserId(userDto.getUserId());
        System.out.println("==删除user的对象==" + sysUser);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", sysUser.getUserId());
        userService.remove(queryWrapper);
        //sys_user_role中间表

        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(userDto.getUserId());
        System.out.println("==删除user的中间表对象==" + sysUserRole);
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("user_id", sysUserRole.getUserId());
        userRoleService.remove(queryWrapper1);
        return ResultEntity.ok("200", "成功");
    }


    @RequestMapping("updateuser")
    @Transactional
    public ResultEntity updateuser(@RequestBody UserDto userDto){
        SysUser user=new SysUser();
        BeanUtils.copyProperties(userDto,user);
//        user.setPassword(MD5Utils.md5(userDto.getPassword()));
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        System.out.println(user);
        userService.updateById(user);

        if (userDto.getJueseids() != null) {
            for (String jueseid : userDto.getJueseids()) {
                System.out.println(jueseid);
                userRoleService.deletebyuserid(userDto.getUserId());
            }

            String[] jueseids = userDto.getJueseids();
            for (String jueseid : jueseids) {
                System.out.println("========" + jueseid);
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(user.getUserId());
                sysUserRole.setRoleId(Long.parseLong(jueseid));
                userRoleService.save(sysUserRole);
            }
            return ResultEntity.ok("200", "编辑成功");
        } else {
            return ResultEntity.ok("200", "编辑失败");
        }


    }


    @RequestMapping("getstatus")
    public ResultEntity getstatus(@RequestBody UserDto userDto) {
        boolean b = true;
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userDto, user);
        System.out.println("=====" + user);
        if (user.getStatus().equals(0)) {
            b = userService.updateById(user);
        }
        if (user.getStatus().equals(1)) {
            b = userService.updateById(user);
        }

        return ResultEntity.ok("状态修改成功", b);
    }

    @RequestMapping("logins")
    public ResultEntity login(@RequestBody UserDto userDto, HttpServletResponse response) {
        return userService.login(userDto, response);
    }


    @RequestMapping("selall")
    public ResultEntity selall() {
        List<SysUser> list = userService.list();
        return ResultEntity.ok(list);
    }


    @RequestMapping("/findByUserName")
    SysUserVo findByUserName(@RequestBody String username) {
        return userService.findByUserName(username);
    }

}
